<!DOCTYPE html>
<html>
<head>
  <script src="/resources/testharness.js"></script>
  <script src="/resources/testharnessreport.js"></script>
  <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
</head>
<body>
<script>
  // This policy allows document.write to work as that's not relevant to what's actually being tested here.
  trustedTypes.createPolicy('default', {createHTML: s => s});
  promise_test(t => {
    document.write(`<svg><script>window.postMessage("first script element executed", "*");`);
    var manipulator = _ => {
      let script = document.body.getElementsByTagName("script")[1];
      if (script) {
        script.appendChild(document.createTextNode('/*byapi*/'));
        document.write('<\/script><script>window.parent.postMessage("second script element executed", "*");<\/script><\/svg>');
      } else {
        t.step_timeout(manipulator, 50);
      }
    }
    manipulator();

    // Now we'll wait for the postMessages to arrive. We expect the iframe's
    // first message to be blocked by Trusted Types, since the manipulator
    // above should have manipulated it (while loading). The second one should
    // pass.
    return new Promise((resolve, reject) => {
      window.addEventListener("message", e => {
        if (e.data.includes("first")) {
          reject("First message should have been blocked: " + e.data);
        } else if (e.data.includes("second")) {
          resolve();
        } else {
          reject("Unknown message: " + e.data);
        }
      });
    });
  }, "Test TT application when manipulating <script> elements during loading.");
</script>
</body>
</html>
